#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include <sys/epoll.h>

#include "socket.h"
#include "pthreadpool.h"
#include "epoll.h"
#include "filedispat.h"
#include "data_packet.h"
#include "like.h"

extern void Connect_procfunc(void *arg);
extern void Message_procfunc(void *arg);
extern void File_Message_procfunc(void *arg);

void Judge_fileinfo_or_chatinfo(Conndata *data)
{
	int ret_mark=-10;
	ret_mark = read_fifo_mark(data->event_fd);
	//printf("mark=%d------\n\n",ret_mark);
	if(ret_mark>=0){
		if(ret_mark==5||ret_mark==6)
			pthreadpool_Taks_add(data->pool,File_Message_procfunc,(void *)data);
		else
			pthreadpool_Taks_add(data->pool,Message_procfunc,(void *)data);
	}else{
		if(ret_mark == -1){
			pthread_mutex_lock(&data->pool->link_lock);
			del_like_user(data->event_fd,head);
			if(on_line_updata(head))
				perr_exit("send error\n");
			epoll_ctl_del(data->event_fd,data->efd_size,head); 
			printf("client[%d] closed connection\n", data->event_fd);
			pthread_mutex_unlock(&data->pool->link_lock);
		}else{
			perror("read n <0 error: "); 
			epoll_ctl(data->efd_size, EPOLL_CTL_DEL, data->event_fd, NULL);		
			close(data->event_fd); 
		}
	}
	
}

int main(int argc,char *argv[])
{
	int listfd,nready;
	int ret,efd,i;
	struct sockaddr_in ser_addr;
	struct epoll_event epoll,ep[OPEN_MAX];
	//socklen_t client=sizeof(struct sockaddr_in);
	threadpool *pool;
	ser_addr = sockaddr_init(ser_addr);

	pool = threadpool_create(20, 50);
	if(pool == NULL)
		perr_exit("pool malloc error!\n");

	head = like_init();

	listfd = socket_init(ser_addr);
	if(listfd ==-1)
		perr_exit("socket error");

	efd = epoll_init(OPEN_MAX);
	if(efd == -1)
		perr_exit("epoll create");

	ret = epoll_ctl_link(listfd,efd,epoll);
	if(ret == -1)
		perr_exit("epoll_ctl error");

	while(1){
		nready = epoll_wait(efd,ep,OPEN_MAX,-1);
		if(nready == -1)
			perr_exit("epoll_wait error");

		for(i=0;i<nready;i++){
			if(!(ep[i].events & EPOLLIN))
				continue;
			if(ep[i].data.fd == listfd){
				Conndata *listdata = malloc(sizeof(Conndata));
				if(listdata == NULL)
					perr_exit("Conndata MALLOC ERROR!\n");
				listdata->event_fd = listfd;
				listdata->efd_size = efd;
				listdata->pool = pool;
				pthreadpool_Taks_add(pool,Connect_procfunc,(void *)listdata);
			}else{
				// printf("\n\n threadool add task \n\n");
				Conndata *clidata = malloc(sizeof(Conndata));
				if(clidata == NULL)
					perr_exit("Conndata MALLOC ERROR!\n");
				clidata->event_fd = ep[i].data.fd;
				clidata->efd_size = efd;
				clidata->pool = pool;
				// int aaa;
				// char pbuf[SOCK_BUF_SIZE];
				// bzero(pbuf,0);
				// aaa = recvn_read_only(clidata->event_fd,pbuf,SOCK_BUF_SIZE);
				// printf("%d^%s\n",aaa,pbuf);
				// sleep(1);
				pthreadpool_Taks_add(pool, Epoll_Detection_profunc , (void *)clidata);
				//Epoll_Detection_profunc((void *)clidata);
			}	
		}
	
	}
	return 0;

}


